﻿#include "systemSetDlg.h"
#include "EagleDeviceMgr.h"
#include "QLabel"
#include "QCheckBox"
#include "common.h"
#include "EagleMainFrame.h"
#include <memory>
#include "QFormLayout"
#include "QMessageBox"
#include <tuple>
#define SET_IPADDR
#undef SET_IPADDR

#ifdef SET_IPADDR
#include "../include/user_define/IpConfig.h"
#endif

systemSetDlg::systemSetDlg(QWidget *parent /*= 0*/)
:QDialog(parent)
{
	ui.setupUi(this);
	EagleMainFrame* caller = qobject_cast<EagleMainFrame*>(parent);
	QVector<TDevWithCCDInfo*>& tDevList = caller->DevList();

	//////////////////////////////////////////////////////////////////////////
	// 对各种设置page 进行创建和插入 [11/4/2016 ejitec]
	
	//1. 通讯方式设置 [11/7/2016 ejitec]
	communicateWidget* netSet = new communicateWidget(this);
	QVBoxLayout* netLayout = new QVBoxLayout(ui.communicationSet);
	netLayout->addWidget(netSet);
	_mPageList.insert(tr("communicationSet"), netSet);

	//2. task 设置
	ui.lineEdit_taskNam->setText(EagleConfigFile::getInstance()->task_name);
	devsTaskSet* taskSetWidget = new devsTaskSet(tDevList, ui.lineEdit_taskNam->text(),this);
	ui.scrollAreaTask->setWidget(taskSetWidget);
	_mPageList.insert(tr("systemSet"), taskSetWidget);
	ui.scrollAreaTask->setBackgroundRole(QPalette::Light);
	connect(ui.lineEdit_taskNam, &QLineEdit::editingFinished, taskSetWidget, [=]()
	{
		// [0-9a-z_]
		QRegExp reg("^\\w{1,32}$", Qt::CaseInsensitive);
		if (!ui.lineEdit_taskNam->text().contains(reg))
		{
			QMessageBox::warning(this, GetMessageBoxTitle(), GetLogFormat(EagleLog_M_Invalid_Task_Name_Alarm));
			//QMessageBox::warning(this, tr("非法任务名"), tr("任务名称:\"%1\" 非法 ...\n仅支持字母，数字，下划线及长度不超过32位.").arg(ui.lineEdit_taskNam->text()));
			return;
		}
		taskSetWidget->setTaskNam(ui.lineEdit_taskNam->text());
	});

	//3. 设置diskMap [11/3/2016 ejitec]
	disksMapWidget* disksWidget = new disksMapWidget(tDevList,this);
	ui.scrollArea->setWidget(disksWidget);
	_mPageList.insert(tr("disMap"), disksWidget);
	ui.scrollArea->setBackgroundRole(QPalette::Light);

	//4. 采集参数设置 [11/7/2016 ejitec]
	camGrabParamSet* camGrabParm = new camGrabParamSet(tDevList, this);
	ui.scrollAreaGrabParam->setWidget(camGrabParm);
	_mPageList.insert(tr("grabParamSet"), camGrabParm);
	ui.scrollAreaGrabParam->setBackgroundRole(QPalette::Light);

	//5. 设备名称及显示顺序设置PAGE [11/7/2016 ejitec]
	AllDevNamSet* devNamPage = new AllDevNamSet(tDevList, this);
	QVBoxLayout* devNamsVLaylout = new QVBoxLayout(ui.devNamSet);
	devNamsVLaylout->addWidget(devNamPage);
	_mPageList.insert(tr("devNamSet"), devNamPage);
}


systemSetDlg::~systemSetDlg()
{
}

void systemSetDlg::on_setDlgOK()
{
	QString strText = ui.tabWidget->currentWidget()->objectName();
	auto it = _mPageList.find(strText);

	if (it != _mPageList.end())
	{
		setPageWidget* page = it.value();
		page->on_setOK();
	}

	this->accept();
}

// 通讯方式设置 需要重新设置网卡和设备[11/7/2016 ejitec]
int communicateWidget::on_setOK()
{
	// 设置
	int conmunication_selection = ui.cmb_choice->currentIndex();
	if (conmunication_selection > CONTROL_WINCAP)
	{
		QMessageBox::warning(this, tr("提示"), tr("Not support %1").arg(ui.cmb_choice->currentText()));
		return 1;
	}

	CEagleDeviceMgr::GetInstance()->ClearDevices();

	int conmu_type = CONTROL_WINCAP;
	if (conmunication_selection == CONTROL_WINCAP)
	{
		conmu_type = CONTROL_WINCAP;
		QStringList eth_names;
		for (int i = 0; i < ui.listWidget->count(); i++)
		{
			eth_names << ui.listWidget->item(i)->text().section(":", 1, 1);
		}
		EagleConfigFile::getInstance()->eth_name = eth_names;
	}
	else if (conmunication_selection == CONTROL_SERIAL)
	{
		conmu_type = CONTROL_SERIAL;
		EagleConfigFile::getInstance()->serial_port = ui.cmb_ctx->currentText();
	}
	else
	{

	}
	//状态栏显示 设置通讯方式为：串口失败，错误码：1    | com1 [11/17/2016 ejitec]
	ControlApiLogger(conmunication_selection != CONTROL_WINCAP, EagleLog_I_Set_Conmunication_Method, ui.cmb_choice->currentText());
	EagleConfigFile::getInstance()->conmunicate_method = QString::number(ui.cmb_choice->currentIndex());
	EagleConfigFile::getInstance()->store();
	
	// 通知主界面重新扫描
	emit g_theApp->evt_netWorkChange();

	return 0;
}

communicateWidget::communicateWidget(QWidget *parent /*= 0*/)
:setPageWidget(parent)
{
	ui.setupUi(this);
	_comStrList.clear();
	for (int i = 0; i < 9; i++)
	{
		_comStrList << QString("COM %1").arg(i + 1);
	}

	_default_selection = EagleConfigFile::getInstance()->conmunicate_method.toInt();
		
	struct eagle_all_netcards netcards;
	memset(&netcards, 0, sizeof(netcards));
	int ret = EagleControl_GetSystemNICs(&netcards);
	if (ret)
	{
		QMessageBox::warning(this, GetMessageBoxTitle(), GetLogFormat(EagleLog_E_Get_NIC_List));
		return;
	}

	for (int i = 0; i < netcards.card_num; i++)
	{
		_netStrList << netcards.cards[i].dev_description;
	}
	ui.cmb_choice->setCurrentIndex(-1);  // 初始化 方面后面的 index变化事件


	connect(ui.cmb_choice, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [this](int n)
	{
		ui.cmb_ctx->clear();

		ui.btn_add->setEnabled(n == CONTROL_WINCAP);
		ui.btn_del->setEnabled(n == CONTROL_WINCAP);

		if (n == CONTROL_SERIAL)
		{
			ui.cmb_ctx->insertItems(0,_comStrList);
			ui.cmb_ctx->setCurrentText(EagleConfigFile::getInstance()->serial_port);
			ui.listWidget->clear();
		}
		else
		{
			ui.cmb_ctx->insertItems(0,_netStrList);
			ui.listWidget->addItems(EagleConfigFile::getInstance()->eth_name);
			freshList();
		}
	});

	connect(ui.btn_add, &QPushButton::clicked, this, [this]()
	{
		QString strItemTxt = ui.cmb_ctx->currentText();
		QList<QListWidgetItem*> items = ui.listWidget->findItems(strItemTxt, Qt::MatchContains);
		if (items.size() == 0)  // 没有则添加
		{
			ui.listWidget->addItem(ui.cmb_ctx->currentText());
			freshList();
		}
	});

	connect(ui.btn_del, &QPushButton::clicked, this, [this]()
	{
		ui.listWidget->takeItem(ui.listWidget->currentRow());
		freshList();
	});
	
	ui.cmb_choice->setCurrentIndex(_default_selection);
}

void communicateWidget::freshList()
{
	for (int i = 0; i < ui.listWidget->count(); i++)
	{
		QString strPre = ui.listWidget->item(i)->text();
		ui.listWidget->item(i)->setText(tr("相机%1:%2").arg(i + 1).arg(strPre.mid(strPre.indexOf(":") + 1)));
	}
}

//////////////////////////////////////////////////////////////////////////
// 各设备相机磁盘映射设置 diskMapWidget [11/3/2016 ejitec]
disksMapWidget::disksMapWidget(QVector<TDevWithCCDInfo*>& devs, QWidget *parent /*= 0*/)
:setPageWidget(parent)
, _tDevsInfo(devs)
{
	_vDisksMap.clear();
	QGridLayout*  gridDisk = new QGridLayout(this);
	gridDisk->setSpacing(10);

	int nRow = 0;
	for (auto it = devs.begin(); it != devs.end(); it++)
	{
		diskMapWidget* diskMap = new diskMapWidget(*it, this);
		gridDisk->addWidget(diskMap, gridDisk->rowCount(), 0);
		_vDisksMap << diskMap;
	}
}

int disksMapWidget::on_setOK()
{
	int nRet = 0;
	int bRet = true;
	for (auto it : _vDisksMap)
	{
		nRet = it->on_setOK();
		if (nRet != 0) bRet = false;
	}

	return bRet ? 0 : -1;
}


diskMapWidget::diskMapWidget(TDevWithCCDInfo* devInfo, QWidget *parent /*= 0*/)
:_tdevInfo(devInfo)
, QWidget(parent)
{
	QGridLayout* gridLayout = new QGridLayout(this);
	gridLayout->setVerticalSpacing(10);
	gridLayout->setHorizontalSpacing(10);
	QLabel* labDev = new QLabel(tr("设备名"), this);
	QLabel* labCam = new QLabel(tr("相机"), this);

	gridLayout->addWidget(labDev, 0, 0);
	gridLayout->setColumnMinimumWidth(0, 100);
	gridLayout->addWidget(labCam, 0, 1);

	int disk_num = 0;

	struct eagle_system_status status = _tdevInfo->m_tStatus;
	disk_num = status.disk_num;

	for (int i = 0; i < disk_num; i++)
	{
		QString strText = QString(tr("磁盘%1\n(%2GB)")).arg(i).arg(status.remained_volume[i]);
		QLabel* diskN = new QLabel(strText, this);
		diskN->setWordWrap(true);  // 支持换行
		gridLayout->addWidget(diskN, 0, 2 + i);
	}
	
	int max_camera_num = _tdevInfo->m_vCCDInfo.size();
	int nValidCnd = count_if(_tdevInfo->m_vCCDInfo.begin(), _tdevInfo->m_vCCDInfo.end(),
		[](TCCDInfo& it)
	{
		return it.m_bValid == true;
	});
	QLabel* labDevNam = new QLabel(_tdevInfo->m_strDevNam, this);
	// 设备
	gridLayout->addWidget(labDevNam, 1, 0, nValidCnd, 1, Qt::AlignVCenter);  // 占用多行

	// 
	for (int i = 0; i < max_camera_num; i++)
	{
		TCCDInfo& info = _tdevInfo->m_vCCDInfo[i];
		if (!_tdevInfo->m_vCCDInfo[i].m_bValid)
		{
			continue;
		}
		QLabel* labCCDNam = new QLabel(info.m_strCCDNam, this);
		gridLayout->addWidget(labCCDNam, i + 1, 1);  // 行增加  列固定 [4/1/2017 ejitec]
	}

	eagle_camera_disk_config diskConfig = _tdevInfo->m_diskMap;

	int nRet = EagleControl_GetCameraDiskMapping(_tdevInfo->m_nDevID, &_tdevInfo->m_diskMap);
	if (!nRet)
	{
		diskConfig = _tdevInfo->m_diskMap;
	}

	// 磁盘多列
	for (int i = 0; i < disk_num; i++)
	{
		QButtonGroup* btnGroup = new QButtonGroup(this);
		for (int j = 0; j < max_camera_num; j++)
		{
			if (!_tdevInfo->m_vCCDInfo[j].m_bValid)
			{
				continue;
			}
			QCheckBox* diskN = new QCheckBox(QString::number(i), this);
			gridLayout->addWidget(diskN, j + 1, i + 2); // 行增加  列随磁盘个数 增加
			int dMap = _tdevInfo->m_diskMap.disk_reign[j];
			if (dMap & (0x1 << i))
			{
				diskN->setChecked(true);
			}
			// 每块磁盘加入 组 互斥
			btnGroup->addButton(diskN, i*max_camera_num + j);  // 对应关系
		}
		btnGroup->setExclusive(false);  // 独占模式 必须 勾选一个 不符合逻辑
		connect(btnGroup, static_cast<void(QButtonGroup::*)(int)>(&QButtonGroup::buttonClicked),
			[=](int id)
		{
			QCheckBox* check = qobject_cast<QCheckBox*>(btnGroup->button(id));
			if (check->isChecked())
			{
				for(QAbstractButton* var : btnGroup->buttons())
				{
					if (var != check)
					{
						var->setChecked(false);
					}
				}
			}
		});

		_vButtons << btnGroup;
	}
	
	QFrame*line = new QFrame(this);
	line->setFrameShape(QFrame::HLine);
	line->setFrameShadow(QFrame::Sunken);
	gridLayout->addWidget(line, gridLayout->rowCount(), 0,1, gridLayout->columnCount(),Qt::AlignTop);
}

diskMapWidget::~diskMapWidget()
{
}

int diskMapWidget::on_setOK()  // 到最后单页的设置
{
	int max_camera_num = _tdevInfo->m_vCCDInfo.size();
	int disk_num = _tdevInfo->m_tStatus.disk_num;

	struct eagle_camera_disk_config config;
	memset(&config, 0x00, sizeof(config));

	int nDsk = 0, j = 0;
	for (auto it : _vButtons)  // 几个磁盘
	{
		int id = it->checkedId();
		if (id != -1)  // checked
		{
			int nCam = id - nDsk*max_camera_num;
			config.disk_reign[nCam] |= (0x1 << nDsk);
		}

		nDsk++;
	}

	int nRet = EagleControl_SetCameraDiskMapping(_tdevInfo->m_nDevID, &config);
	ControlApiLogger(nRet, EagleLog_C_Set_Disk_Assign);

	return nRet;
}

// 设备及任务设置 [11/7/2016 ejitec]
devsTaskSet::devsTaskSet(QVector<TDevWithCCDInfo*>& devs, QString strTask, QWidget *parent /*= 0*/)
:setPageWidget(parent)
, m_strTaskNam(strTask)
, _tDevsInfo(devs)
{
	QGridLayout* tastGridL = new QGridLayout(this);
	//tastGridL->setSpacing(10);
	tastGridL->setVerticalSpacing(20);
	tastGridL->setHorizontalSpacing(150);
	QLabel* labDisk = new QLabel(tr("磁盘报警阈值(GB)"), this);
	QLabel* labDev = new QLabel(tr("设备名称"), this);
	QLabel* labAddr = new QLabel(tr("设备地址"),this);
	tastGridL->addWidget(labDev, 0, 0, Qt::AlignTop | Qt::AlignTop);
	tastGridL->addWidget(labDisk, 0, 1, Qt::AlignLeft | Qt::AlignTop);
	tastGridL->addWidget(labAddr, 0, 2, Qt::AlignHCenter | Qt::AlignTop);
	tastGridL->setColumnStretch(0, 0);
	tastGridL->setColumnStretch(1, 5);
	tastGridL->setColumnStretch(2, 5);
	tastGridL->setRowStretch(0, 0);
	for (auto it: _tDevsInfo)
	{
		int nRow = tastGridL->rowCount();
		QLabel* labDevN = new QLabel(it->m_strDevNam, this);
		tastGridL->addWidget(labDevN, nRow, 0, Qt::AlignTop);
		QComboBox* cmb = new QComboBox(this);
		cmb->addItems(QString(tr("30|40|50|60|70|80")).split("|"));
		cmb->setCurrentText(CEagleDeviceMgr::GetInstance()->GetDiskThreshold(it->m_nDevID));
		cmb->setMaximumWidth(40);
		tastGridL->addWidget(cmb, nRow, 1, Qt::AlignTop | Qt::AlignLeft);
		m_diskYZ.insert(it->m_strDevNam, cmb);
		QHBoxLayout* hLay = new QHBoxLayout();
		QLineEdit* lineIP = new QLineEdit(this);
		QLineEdit* linePort = new QLineEdit(tr("2200"),this);
		linePort->setReadOnly(true);
		//lineIP->setInputMask("000.000.000.000");
		//lineIP->setValidator()
		hLay->addWidget(lineIP);
		hLay->addWidget(linePort);
		hLay->setSpacing(2);
		m_DevAddr.insert(it->m_strDevNam, hLay);
		tastGridL->addLayout(hLay, nRow, 2, Qt::AlignHCenter | Qt::AlignTop);
#ifdef SET_IPADDR
		eagle_ip_config  ipConfig = { 0 };
		int nRet = EagleControl_GetDeviceCurrentIpAddress(it->m_nDevID, &ipConfig);
		lineIP->setText(inet_ntoa(*(struct in_addr*)(&ipConfig.ip_addr)));
		//lineIP->setValidator(new QIntValidator());
		linePort->setValidator(new QIntValidator(1000, 65535));
		linePort->setText(QString::number(ntohs(ipConfig.port_num)));
#endif
		QFrame*line = new QFrame(this);
		line->setFrameShape(QFrame::HLine);
		line->setFrameShadow(QFrame::Sunken);
		//qDebug() << "tastGridL RowCntB:" << tastGridL->rowCount();
		tastGridL->addWidget(line, tastGridL->rowCount(), 0,1, 3,  Qt::AlignTop);
		//qDebug() << "tastGridL RowCntA:" << tastGridL->rowCount();
		//tastGridL->setRowStretch(i, 5);
	}
}

int devsTaskSet::on_setOK()
{
	for (auto it : _tDevsInfo)
	{
		QString strText = (m_diskYZ.value(it->m_strDevNam))->currentText();
		if (strText == "")
		{
			strText = tr("70");
		}

		if (EagleConfigFile::getInstance()->disk_threshold != strText)
		{
			// 对应设备的 阈值信息 由内部管理，非sdk管理
			CEagleDeviceMgr::GetInstance()->SetDiskThreshold(it->m_nDevID, strText);
			EagleConfigFile::getInstance()->disk_threshold = strText;
		}
	}

	for (auto it : _tDevsInfo)
	{
		QHBoxLayout* lay = m_DevAddr.value(it->m_strDevNam);
		QLineEdit* lineIP = qobject_cast<QLineEdit* >(lay->itemAt(0)->widget());
		QLineEdit* linePort = qobject_cast<QLineEdit* >(lay->itemAt(1)->widget());
#ifdef SET_IPADDR
		eagle_ip_config  ipConfig = { 0 };
		//cout << qPrintable(lineIP->text()) << endl;
		ipConfig.ip_addr = inet_addr(qPrintable(lineIP->text()));
		ipConfig.port_num = htons(linePort->text().toUShort());
		int nRet = EagleControl_SetDeviceNewIpAddress(it->m_nDevID,&ipConfig);
#endif
		
	}

	if (m_strTaskNam != EagleConfigFile::getInstance()->task_name)
	{
		EagleConfigFile::getInstance()->task_name = m_strTaskNam;
		EagleConfigFile::getInstance()->store();
	}

	return 0;
}


// 设备和相机名称、有效性设置 [11/4/2016 ejitec]
ADevNamsSet::ADevNamsSet(TDevWithCCDInfo* dev, QWidget *parent /*= 0*/)
:_tdevInfo(dev)
, setPageWidget(parent)
{
	_formLayOut = new QFormLayout(this);
	
	_lineEditDev = new QLineEdit(_tdevInfo->m_strDevNam, this);
	_lineEditDev->setMaximumWidth(120);
	_formLayOut->addRow(_tdevInfo->m_strDevNam, _lineEditDev);

	int i = 0;
	for (auto it : _tdevInfo->m_vCCDInfo)
	{
		bool bValid = EagleControl_IsCameraValid(_tdevInfo->m_nDevID, it.m_tInfo.camera_no);
		QCheckBox* ccdCheck = new QCheckBox(QString(tr("相机%1")).arg(i), this);
		ccdCheck->setChecked(bValid);
		QLineEdit* lineCCD = new QLineEdit(it.m_strCCDNam, this);
		lineCCD->setMaximumWidth(120);
		lineCCD->setEnabled(bValid);
		_formLayOut->addRow(ccdCheck, lineCCD);
		i++;
		_vNameList << lineCCD;

		connect(ccdCheck, &QCheckBox::stateChanged, lineCCD, [=](int n)
		{
			lineCCD->setEnabled(n == Qt::Checked);
		});
	}

	QFrame*line = new QFrame(this);
	line->setFrameShape(QFrame::HLine);
	line->setFrameShadow(QFrame::Sunken);
	// 增加分割线 跨行占用
	_formLayOut->setWidget(_formLayOut->rowCount(), QFormLayout::SpanningRole, line);
	//_formLayOut->addRow(line);
}

int ADevNamsSet::on_setOK()
{
	// 设置设备名称
	if (_tdevInfo->m_strDevNam != _lineEditDev->text())
	{
		wchar_t wChar[128] = { 0 };
		_lineEditDev->text().toWCharArray(wChar);
		EagleControl_SetDeviceName(_tdevInfo->m_nDevID, wChar);
	}

	// 设置CCD
	auto it = _tdevInfo->m_vCCDInfo.begin();
	int _device_id = _tdevInfo->m_nDevID;
	
	for (int i = 0; it != _tdevInfo->m_vCCDInfo.end(); i++, it++)
	{
		wchar_t wChar[128] = { 0 };
		QString strText = qobject_cast<QLineEdit*>(_vNameList[i])->text();
		// 根据 第二列获取第一列
		bool bCheck = qobject_cast<QCheckBox*>(_formLayOut->labelForField(_vNameList[i]))->isChecked();
		
		if (it->m_strCCDNam != strText)
		{
			strText.toWCharArray(wChar);
			int nRet1 = EagleControl_SetCameraName(_device_id, it->m_tInfo.camera_no, wChar);
		}
		
		if (EagleControl_IsCameraValid(_device_id, it->m_tInfo.camera_no) != bCheck)
		{
			EagleControl_SetDeviceCameraValid(_device_id, it->m_tInfo.camera_no, bCheck);
		}
	}

	return 0;
}

AllDevNamSet::AllDevNamSet(QVector<TDevWithCCDInfo*>& devs, QWidget *parent /*= 0*/)
:setPageWidget(parent)
, _tDevsInfo(devs)
{
	ui.setupUi(this);

	ui.listWidget_dev->setSelectionMode(QAbstractItemView::SelectionMode::SingleSelection);
	QVBoxLayout* VLayOut = new QVBoxLayout(ui.scrollWidget);
	VLayOut->setSpacing(20);
	ui.scrollArea->setBackgroundRole(QPalette::Light);

	// 添加设备
	for (auto it : _tDevsInfo)
	{
		ui.listWidget_dev->addItem(it->m_strDevNam);
		ADevNamsSet* aDev = new ADevNamsSet(it, this);
		_vDevSets << aDev;
		VLayOut->addWidget(aDev);
	}

	// 多行选择 暂时不支持 
	connect(ui.btn_UP, &QPushButton::clicked, this, [this]()
	{
		QList<QListWidgetItem*> items = ui.listWidget_dev->selectedItems();
		if (items.size() == 0)
		{
			return;
		}

		for(QListWidgetItem* var : items)
		{
			qDebug() << var->text();
		}

		QListWidgetItem *item = ui.listWidget_dev->takeItem(ui.listWidget_dev->currentRow() - 1);
		if (item)
		{
			ui.listWidget_dev->addItem(item);
		}
	});

	connect(ui.btn_Down, &QPushButton::clicked, this, [this]()
	{
		QList<QListWidgetItem*> items = ui.listWidget_dev->selectedItems();
		if (items.size() == 0)
		{
			return;
		}
		QListWidgetItem *item = ui.listWidget_dev->takeItem(ui.listWidget_dev->currentRow() + items.size());
		if (item)
		{
			ui.listWidget_dev->insertItem(ui.listWidget_dev->currentRow(),item);
		}
	});
}

int AllDevNamSet::on_setOK()
{
	for (auto it : _vDevSets)
	{
		it->on_setOK();
	}

	int nCnt = ui.listWidget_dev->count();
	QStringList sort_names;
	for (int i = 0; i < nCnt; i++)
	{
		sort_names << ui.listWidget_dev->item(i)->text();
	}

	EagleConfigFile::getInstance()->device_sort_order = sort_names;
	EagleConfigFile::getInstance()->store();

	emit g_theApp->evt_netWorkChange(); // 窗口刷新

	return 0;
}

// 采集参数设置 [11/7/2016 ejitec]   scoll --> widget --> goup --> 
camGrabParamSet::camGrabParamSet(QVector<TDevWithCCDInfo*>& devs, QWidget *parent /*= 0*/)
:setPageWidget(parent)
, _tDevsInfo(devs)
, _pCLs(nullptr)
, _pSdis(nullptr)
{
	_vLPanel = new QVBoxLayout(this);
	_vLPanel->setSpacing(10);

	QString strWidths = QString(tr(""));
	int i = 0;

	for (auto& it : _tDevsInfo)
	{
		if (it->m_device_type == EDeviceTypeCL)
		{
			if (_pCLs == nullptr)
			{
				_pCLs = new AllCLCCDParmConfig(this);
				_vLPanel->addWidget(_pCLs);

			}
			_pCLs->InsertOneCCD(*it);
		}
		else if (it->m_device_type == EDeviceTypeSDI)
		{
			if (_pSdis == nullptr)
			{
				_pSdis = new AllSDICCDParmConfig(this);
				_vLPanel->addWidget(_pSdis);
			}
			_pSdis->InsertOneCCD(*it);
		}
	}
}

int camGrabParamSet::on_setOK()
{
	if (_pCLs)
	{
		_pCLs->on_setOK();
	}

	if (_pSdis)
	{
		_pSdis->on_setOK();
	}

	return 0;
}


// CL 相机设置
AllCLCCDParmConfig::AllCLCCDParmConfig(QWidget *parent /*= 0*/)
:setPageWidget(parent)
{
	_vLayout = new QVBoxLayout(this);  // 设置窗口设置布局
	
	_group = new QGroupBox(tr("CameraLink相机参数设置"), this);
	_group->setAlignment(Qt::AlignHCenter|Qt::AlignTop);
	_group->setStyleSheet("QGroupBox {border:1px solid;border-color:darkblue;color:darkred;\
						  						  	font:bold Consolas large;font-size:12px;}");
	_paramGridL = new QGridLayout(_group);
	_paramGridL->setVerticalSpacing(10);
	_paramGridL->setHorizontalSpacing(10);
	_group->setLayout(_paramGridL);
	QString strCLNams = QString(tr("设备名称|相机|模式|列数|行数|Taps&色深|抽行抽列比例"));

	int nCol = 0;
	int nRow = _paramGridL->rowCount();  // grid 初始化时就有一行
	for (QString var : strCLNams.split("|"))
	{
		QLabel* labelCol = new QLabel(var, this);
		_paramGridL->addWidget(labelCol, 0, nCol,Qt::AlignBottom);
		nCol++;
	}
	_paramGridL->setRowMinimumHeight(0, 20);

	QFrame*line = new QFrame(_group);
	line->setFrameShape(QFrame::HLine);
	line->setFrameShadow(QFrame::Sunken);
	//_paramGridL->addWidget(line, _paramGridL->rowCount(), 0, _paramGridL->columnCount(), 0, Qt::AlignVCenter);
	_paramGridL->addWidget(line, 1, 0, 1,_paramGridL->columnCount(),Qt::AlignVCenter);
	_paramGridL->setRowMinimumHeight(_paramGridL->rowCount(), 10);

	_vLayout->addWidget(_group);
	_vLayout->addStretch(1);
}

void AllCLCCDParmConfig::InsertOneCCD(TDevWithCCDInfo& it)
{
	int i = _paramGridL->rowCount();
	int nLoop = 0;

	for (TCCDInfo& it2 : it.m_vCCDInfo)
	{
		if (!it2.m_bValid)
		{
			continue;
		}
		eagle_capture_config* ccd_config = &(it2.m_tInfo);
		// 获取模式
		long cl_mode = GetCameraMode(ccd_config->taps, ccd_config->color_depth);
		i = _paramGridL->rowCount();
		QLabel* labDevN = new QLabel(it.m_strDevNam, this);
		_paramGridL->addWidget(labDevN, i, 0, Qt::AlignLeft | Qt::AlignTop);
		QLabel* labCCD = new QLabel(it2.m_strCCDNam, this);
		_paramGridL->addWidget(labCCD, i, 1, Qt::AlignLeft | Qt::AlignTop);

		QComboBox* cmbMode = new QComboBox(this);
		cmbMode->addItem(CL_Mode_Str[(int)CameraModeTypeBase]);
		cmbMode->addItem(CL_Mode_Str[(int)CameraModeTypeMedium]);
		cmbMode->addItem(CL_Mode_Str[(int)CameraModeTypeFull]);
		cmbMode->setCurrentIndex(-1);
		_paramGridL->addWidget(cmbMode, i, 2, Qt::AlignLeft | Qt::AlignTop);

		QComboBox* cmbColR = new QComboBox(this);
		cmbColR->addItems(EagleConfigFile::getInstance()->support_column);
		cmbColR->setEditable(true);
		_paramGridL->addWidget(cmbColR, i, 3, Qt::AlignLeft | Qt::AlignTop);
		
		QComboBox* cmbLine = new QComboBox(this);
		cmbLine->addItems(EagleConfigFile::getInstance()->support_line);
		cmbLine->setEditable(true);
	
		_paramGridL->addWidget(cmbLine, i, 4, Qt::AlignLeft | Qt::AlignTop);

		QComboBox* cmbTaps = new QComboBox(this);
		//cmbTaps->addItems(QString("1T8|2T8|3T8|1T10|2T10|1T12|2T12|1T14|1T16").split("|"));
		cmbTaps->setEditable(true);
		_paramGridL->addWidget(cmbTaps, i, 5, Qt::AlignLeft | Qt::AlignTop);
		connect(cmbMode, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), cmbTaps,
			[=]()
		{
			long cl_mode = cmbMode->currentIndex();
			cmbTaps->clear();
			if (cl_mode == CameraModeTypeBase)
			{
				cmbTaps->addItems(EagleConfigFile::getInstance()->base_support_tapbits);
			}
			else if (cl_mode == CameraModeTypeFull)
			{
				cmbTaps->addItems(EagleConfigFile::getInstance()->full_support_tapbits);
			}
			else
			{
				cmbTaps->addItems(EagleConfigFile::getInstance()->medium_support_tapbits);
			}
		});

		cmbMode->setCurrentIndex(cl_mode);

		cmbColR->setCurrentText(QString::number(ccd_config->column));
		cmbLine->setCurrentText(QString::number(ccd_config->line));
		cmbTaps->setCurrentText(QString("%1T%2").arg(ccd_config->taps).arg(ccd_config->color_depth));
		QComboBox* cmbCH = new QComboBox(this);
		cmbCH->addItems(EagleConfigFile::getInstance()->support_shrink_level);
		_paramGridL->addWidget(cmbCH, i, 6, Qt::AlignLeft | Qt::AlignTop);
		//paramGridL->setRowStretch(i, 5);
		char shrink_value = 0;
		if (EagleControl_GetCameraRealtimeShrinkLevel(it.m_nDevID, ccd_config->camera_no, &shrink_value) == 0)
		{
			cmbCH->setCurrentText(QString::number(shrink_value));
		}

		if (ccd_config->capture_status > ECaptureReady)
		{
			this->setEnabled(false);
		}

		pfCLGetConfig pf = [=](CameraModeType &cl_mode, long &column, long &line, long &bits,
			long &rate, long &taps, unsigned long &shrink_level, bool& bEnable)
		{
			bEnable = this->isEnabled();

			QString select_mode = cmbMode->currentText();
			for (unsigned long i = 0; i < CL_Mode_Str.size(); i++) 
			{
				if (select_mode == CL_Mode_Str[i]) 
				{
					cl_mode = (CameraModeType)i;
					break;
				}

				cl_mode = CameraModeTypeNull;
			}
			column = cmbColR->currentText().toLong();
			line = cmbLine->currentText().toLong();

			QString tapbits = cmbTaps->currentText();
			if (tapbits == "xTx") 
			{
				taps = 'x';
				bits = 'x';
			}
			else 
			{
				taps = tapbits.section("T", 0, 0).toInt();
				bits = tapbits.section("T", 1, 1).toInt();
			}
			
			shrink_level = cmbCH->currentText().toLong();
		};

		m_tpList.push_back(std::make_tuple(it.m_nDevID, &it2, pf));
	}
}

int AllCLCCDParmConfig::on_setOK()
{
	eagle_capture_config config;
	
	long column, line, bits, rate, taps;
	unsigned long shrink_level = 0;
	CameraModeType mode;
	bool bEnable = false;

	for (auto it = m_tpList.begin(); it != m_tpList.end(); it++)
	{
		auto pf = std::get<2>(*it);
		pf(mode, column, line, bits, rate, taps, shrink_level, bEnable);
		if (!bEnable)
		{
			continue;
		}

		config.camera_no = std::get<1>(*it)->m_tInfo.camera_no;
		config.column = column;
		config.line = line;
		config.color_depth = bits;
		config.frame_rate = rate;
		config.taps = taps;

		int ret = EagleControl_SetCameraCaptureParam(std::get<0>(*it), &config);
		if (ret == 0)
		{
			std::get<1>(*it)->m_tInfo = config;
		}

		EagleControl_SetCameraRealtimeShrinkLevel(std::get<0>(*it),config.camera_no, (char)shrink_level);
		ControlApiLogger(ret, EagleLog_C_Set_Ccd_Param, QString::number((char)shrink_level));
	}

	return 0;
}


// sdi 相机  [11/18/2016 ejitec]
AllSDICCDParmConfig::AllSDICCDParmConfig(QWidget *parent /*= 0*/)
:setPageWidget(parent)
{
	_group = new QGroupBox(tr("SDI相机参数设置"), this);
	_vLayout = new QVBoxLayout(this);
	_group->setStyleSheet("QGroupBox {border:1px solid;border-color:darkblue;color:darkred;\
						  				font:bold Consolas large;font-size:12px;}");
	_paramGridL = new QGridLayout(_group);
	_paramGridL->setVerticalSpacing(4);
	_paramGridL->setHorizontalSpacing(5);

	QString strSDINams = QString(tr("设备名称|相机|采样样式|色深|分辨率"));

	int nCol = 0;
	int nRow = _paramGridL->rowCount();
	for (QString var : strSDINams.split("|"))
	{
		QLabel* labelCol = new QLabel(var, this);
		_paramGridL->addWidget(labelCol, 0, nCol, Qt::AlignBottom);
		//_paramGridL->addWidget(labelCol, 0, nCol, Qt::AlignLeft | Qt::AlignTop);
		nCol++;
	}
	_paramGridL->setRowMinimumHeight(_paramGridL->rowCount(), 10);

	QFrame*line = new QFrame(this);
	line->setFrameShape(QFrame::HLine);
	line->setFrameShadow(QFrame::Sunken);
	_paramGridL->addWidget(line, _paramGridL->rowCount(), 0, 1, _paramGridL->columnCount(), Qt::AlignVCenter);
	_paramGridL->setRowMinimumHeight(_paramGridL->rowCount(), 10);

	_vLayout->addWidget(_group);
	_vLayout->addStretch(1);
}

void AllSDICCDParmConfig::InsertOneCCD(TDevWithCCDInfo& it)
{
	int i = 0;
	for (TCCDInfo& it2 : it.m_vCCDInfo)
	{
		if (!it2.m_bValid)
		{
			continue;
		}
		i = _paramGridL->rowCount();
		// "设备名称|相机|采样样式|色深|分辨率"
		eagle_capture_config* ccd_config = &(it2.m_tInfo);

		QLabel* labDevN = new QLabel(it.m_strDevNam, this);
		_paramGridL->addWidget(labDevN, i, 0, Qt::AlignLeft | Qt::AlignTop);
		QLabel* labCCD = new QLabel(it2.m_strCCDNam, this);
		_paramGridL->addWidget(labCCD, i, 1, Qt::AlignLeft | Qt::AlignTop);

		// 采样格式
		QComboBox* cmbSample = new QComboBox(this);
		for (int tmp = SDICameraModeTypeYCbCr422_I; tmp <= SDICameraModeTypeNotGeneric; tmp++)
			cmbSample->addItem(SDI_Mode_Str[tmp]);

		int sdi_mode = CEagleDeviceMgr::GetInstance()->GetSdiMode(it.m_nDevID) - 1;
		cmbSample->setCurrentIndex(sdi_mode);
		_paramGridL->addWidget(cmbSample, i, 2, Qt::AlignLeft | Qt::AlignTop);
		// 色深
		QComboBox* cmbBits = new QComboBox(this);
		cmbBits->setCurrentText(QString::number(ccd_config->color_depth));
		_paramGridL->addWidget(cmbBits, i, 3, Qt::AlignLeft | Qt::AlignTop);
		// 分辨率
		QComboBox* cmbFrame = new QComboBox(this);

		int size = sizeof(currentSupportResolution) / sizeof(SDIResolution);
		for (int ii = 0; ii < size; ii++)
		{
			cmbFrame->addItem(QString::number(currentSupportResolution[ii].line));
		}
		cmbFrame->setCurrentText(QString::number(ccd_config->line));
		_paramGridL->addWidget(cmbFrame, i, 4, Qt::AlignLeft | Qt::AlignTop);

		if (ccd_config->capture_status > ECaptureReady)
		{
			this->setEnabled(false);
		}

		pfSdiGetConfig pf = [=](int&sdi_mode, long &column, long &line, long &bits, bool& bEnable)
		{
			bEnable = this->isEnabled();
			sdi_mode = cmbSample->currentIndex() + 1;
			bits = cmbBits->currentText().toLong();
			line = cmbFrame->currentText().toLong();

			int size = sizeof(currentSupportResolution) / sizeof(SDIResolution);
			for (int i = 0; i < size; i++)
			{
				if (line == currentSupportResolution[i].line)
				{
					column = currentSupportResolution[i].column * 2;
				}
			}
		};

		m_tpList.push_back(std::make_tuple(it.m_nDevID, &it2, pf));
			
	}
}

int AllSDICCDParmConfig::on_setOK()
{
	long column, line, bits;
	int mode;  // SDICameraModeType
	bool bEnable = false;

	for (auto it = m_tpList.begin(); it != m_tpList.end(); it++)
	{
		auto pf = std::get<2>(*it);
		pf(mode, column, line, bits, bEnable);
		if (bEnable)
		{
			continue;
		}

		eagle_capture_config config;
		config.camera_no = std::get<1>(*it)->m_tInfo.camera_no;
		config.column = column;
		config.line = line;
		config.color_depth = bits;
		config.frame_rate = 0;
		config.taps = 2;
		CEagleDeviceMgr::GetInstance()->SetSdiMode(std::get<0>(*it), mode);
		int ret = EagleControl_SetCameraCaptureParam(std::get<0>(*it), &config);
		if (ret == 0)
		{
			std::get<1>(*it)->m_tInfo = config;
		}
		ControlApiLogger(ret, EagleLog_C_Set_Ccd_Param, QString::number(config.camera_no));
	}

	return 0;
}


